import React from 'react'
import { render } from 'react-dom'
import { match, Router, useRouterHistory } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'

import Cookie from 'tiny-cookie'
import apiInfo from 'helper/apiInfo'
import Store from 'view/store'
import providesStore from 'view/store/providesStore'
import ContextProvider from 'view/components/ContextProvider'
import moment from 'moment'

import rootRoute from 'view/integralmall/routes'

// 样式放底部，覆盖组件的样式
import '../css/main.less'

window.apiInfo = apiInfo;

// 处理时间
moment.locale('zh-cn');
const time = typeof performance !== 'undefined' ? performance.timing.responseStart : new Date().getTime();
const dt = time - /*moment('2016-06-25 18:30:00')//*/G.context.time;

G.context.dt = Math.abs(dt) > 1000 ? dt : 0;
moment.serverNow = function() {
	return moment() - G.context.dt;
};
// 使用 store
const userFlux = new Store('user', G.context.user, {
	remote: (info) => ({
		cmd: 'getUserInfo',
		params: {
			mobile: info.mobile
		}
	})
});

// 需要放在 createElement 外面，否则每次 createElement 生成不同的 class
let Provider = ContextProvider;
Provider = providesStore(userFlux.store, Provider);

function createElement(Component, props) {
	return <Provider userAction={userFlux.actions}>
		<Component {...props} />
	</Provider>;
}

function lazyRender(history, routes) {

	const { pathname, search, hash } = window.location

	match({
		routes,
		history
	}, (error, redirectLocation, renderProps) => {

		if (redirectLocation) {
			history.replace(redirectLocation);
			// redirect and re render
			lazyRender(history, routes)
		} else {
			render(
				<Router history={history} {...renderProps} createElement={createElement} />,
				document.getElementById('react-wraper')
			)
		}
	})
}

const history = G.history = useRouterHistory(createBrowserHistory)({
	basename: G.root
});
lazyRender(history, rootRoute({
	userStore: userFlux.store
}));
